package com.nulp.psycho.web.servlet;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nulp.psycho.db.model.User;
import com.nulp.psycho.db.service.UserService;
import com.nulp.psycho.hash.MD5;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("userLogin");
		String password = request.getParameter("userPassword");

		UserService us = new UserService();
		User user = us.getUserByLoginAndPassword(login, MD5.getHash(password));
		
		if (user != null) {
			if (user.getConfirmationStatus()) {

				request.getSession(true).setAttribute("user", user);
				Cookie cookie = new Cookie("login", user.getLogin());
				cookie.setMaxAge((int) TimeUnit.MINUTES.toMillis(5));
				response.addCookie(cookie);
				request.getSession().setAttribute("user", user);
				response.getWriter().println("");
			} else {
				response.getWriter().println("Your account is not confirm");
			}
		} else {
			response.getWriter().println("Bad login or password");
		}

	}

}
